"""
基本面分析智能体

负责股票基本面分析，包括财务指标分析、行业分析、公司价值评估等
"""

from agno.agent import Agent
from ..utils.model_factory import create_model
from typing import Dict, Any, Optional
import logging
from datetime import datetime
from ..tools.akshare_client import AkShareClient
from ..tools.llm_client import LLMClient
from ..models.analysis_results import FundamentalAnalysis

logger = logging.getLogger(__name__)


class FundamentalAnalystAgent:
    """基本面分析智能体类"""
    
    def __init__(self, model_id: str = "deepseek-chat"):
        """
        初始化基本面分析智能体
        
        Args:
            model_id: LLM模型ID
        """
        self.akshare_client = AkShareClient()
        self.llm_client = LLMClient()
        
        # 定义基本面分析工具
        def analyze_fundamentals(agent: Agent, ticker: str) -> str:
            """
            进行基本面分析
            
            Args:
                ticker: 股票代码
                
            Returns:
                str: 基本面分析结果
            """
            try:
                logger.info(f"开始基本面分析: {ticker}")
                # 从 Workflow 的共享状态中获取收集的数据
                from ..models.market_data import FinancialMetrics, MarketData

                if not agent.workflow_session_state or "collected_data" not in agent.workflow_session_state:
                    return f"尚未找到收集的数据，请先运行市场数据收集智能体。"

                collected = agent.workflow_session_state["collected_data"]
                if ticker not in collected:
                    return f"未找到 {ticker} 的收集数据，请先收集该股票的数据。"

                summary = collected[ticker].get("summary", {})
                financial_metrics_dict = summary.get("financial_data", {})
                market_data_dict = summary.get("realtime_data", {})

                financial_metrics = FinancialMetrics(**financial_metrics_dict)
                market_data = MarketData(**market_data_dict)

                if not financial_metrics_dict or not market_data_dict:
                    return f"{ticker} 的收集数据不完整，请先确保已完成数据收集。"

                # 构建分析上下文
                context_data = {
                    "ticker": ticker,
                    "financial_metrics_with_descriptions": self._add_financial_metrics_descriptions(financial_metrics.model_dump() if financial_metrics else {}),
                    "market_data_with_descriptions": self._add_market_data_descriptions(market_data.model_dump() if market_data else {}),
                    "analysis_date": datetime.now().strftime("%Y-%m-%d")
                }
                
                # 使用LLM进行基本面分析
                analysis_prompt = f"""请对股票 {ticker} 进行详细的基本面分析。

请从以下维度进行分析：
1. 盈利能力分析（净利润、ROE、净利率等）
2. 成长性分析（收入增长、利润增长等）
3. 财务健康状况（负债率、流动比率等）
4. 估值水平分析（PE、PB、PS等）
5. 投资价值评估

请给出：
- 基本面信号（bullish/bearish/neutral）
- 置信度（0-1）
- 详细的分析推理
- 投资建议

请用中文回答，格式要清晰易读。"""
                
                llm_analysis = self.llm_client.analyze_with_llm(
                    prompt=analysis_prompt,
                    context_data=context_data,
                    analysis_type="fundamental"
                )
                
                # 计算评分
                scores = self._calculate_fundamental_scores(financial_metrics)
                # print(scores)
                # print('-'*100)
                
                # 确定信号和置信度
                signal, confidence = self._determine_signal_and_confidence(scores)
                
                # 创建分析结果
                analysis = FundamentalAnalysis(
                    signal=signal,
                    confidence=confidence,
                    reasoning={"llm_analysis": llm_analysis, "scores(10分制)": scores},
                    profitability_score=scores.get("profitability", 0),
                    growth_score=scores.get("growth", 0),
                    financial_health_score=scores.get("financial_health", 0),
                    valuation_score=scores.get("valuation", 0),
                    # key_metrics=financial_metrics.model_dump() if financial_metrics else {}
                )
                
                # 保存分析结果
                if "fundamental_analysis" not in agent.workflow_session_state:
                    agent.workflow_session_state["fundamental_analysis"] = {}

                agent.workflow_session_state["fundamental_analysis"][ticker] = {
                    "analysis": analysis.model_dump(),
                    "realtime_data": self._add_market_data_descriptions(market_data.model_dump() if market_data else {}),
                    "financial_data": self._add_financial_metrics_descriptions(financial_metrics.model_dump() if financial_metrics else {}),
                    "analysis_time": datetime.now().isoformat()
                }
                print(agent.workflow_session_state)
                
                # 生成报告
                report = f"""基本面分析报告 - {ticker}

**分析结论**
- 基本面信号: {signal.upper()}
- 置信度: {confidence:.1%}

**关键评分**
- 盈利能力: {scores.get('profitability', 0):.1f}/10
- 成长性: {scores.get('growth', 0):.1f}/10  
- 财务健康: {scores.get('financial_health', 0):.1f}/10
- 估值水平: {scores.get('valuation', 0):.1f}/10

**关键财务指标**
- 净资产收益率: {financial_metrics.return_on_equity:.2%}
- 市盈率: {financial_metrics.pe_ratio:.1f}
- 市净率: {financial_metrics.price_to_book:.2f}
- 市销率: {financial_metrics.price_to_sales:.2f}
- 每股收益: {financial_metrics.earnings_per_share:.2f}元

**AI深度分析**
{llm_analysis}

**投资建议**
基于基本面分析，当前{signal}信号，建议{'买入' if signal == 'bullish' else '卖出' if signal == 'bearish' else '观望'}。
置信度为{confidence:.1%}，请结合技术面和市场情绪做出最终决策。

分析时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"""
                
                logger.info(f"基本面分析完成: {ticker}")
                return report
                
            except Exception as e:
                error_msg = f"基本面分析失败: {str(e)}"
                logger.error(error_msg)
                return error_msg
        
        def get_fundamental_summary(agent: Agent) -> str:
            """
            获取基本面分析摘要
            
            Returns:
                str: 基本面分析摘要
            """
            if "fundamental_analysis" not in agent.workflow_session_state:
                return "尚未进行任何基本面分析"
            
            analyses = agent.workflow_session_state["fundamental_analysis"]
            summary_lines = ["📊 基本面分析摘要:"]
            
            for ticker, data in analyses.items():
                analysis = data.get("analysis", {})
                signal = analysis.get("signal", "unknown")
                confidence = analysis.get("confidence", 0)
                analysis_time = data.get("analysis_time", "unknown")
                
                signal_emoji = "🟢" if signal == "bullish" else "🔴" if signal == "bearish" else "🟡"
                summary_lines.append(f"- {ticker}: {signal_emoji} {signal.upper()} (置信度: {confidence:.1%}) [{analysis_time}]")
            
            return "\n".join(summary_lines)
        
        def compare_fundamentals(agent: Agent, tickers: str) -> str:
            """
            比较多个股票的基本面
            
            Args:
                tickers: 股票代码列表，用逗号分隔
                
            Returns:
                str: 基本面比较结果
            """
            ticker_list = [t.strip() for t in tickers.split(",")]
            
            if "fundamental_analysis" not in agent.workflow_session_state:
                return "尚未进行任何基本面分析，请先分析相关股票"
            
            analyses = agent.workflow_session_state["fundamental_analysis"]
            comparison_lines = ["📊 基本面比较:"]
            
            for ticker in ticker_list:
                if ticker in analyses:
                    analysis = analyses[ticker]["analysis"]
                    signal = analysis.get("signal", "neutral")
                    confidence = analysis.get("confidence", 0)
                    profitability = analysis.get("profitability_score", 0)
                    growth = analysis.get("growth_score", 0)
                    
                    signal_emoji = "🟢" if signal == "bullish" else "🔴" if signal == "bearish" else "🟡"
                    comparison_lines.append(
                        f"- {ticker}: {signal_emoji} {signal.upper()} "
                        f"(置信度: {confidence:.1%}, 盈利: {profitability:.1f}, 成长: {growth:.1f})"
                    )
                else:
                    comparison_lines.append(f"- {ticker}: ❓ 未分析")
            
            return "\n".join(comparison_lines)
        
        # 创建Agno智能体
        self.agent = Agent(
            name="Fundamental Analyst Agent",
            role="股票基本面分析专家",
            model=create_model(model_id),
            tools=[analyze_fundamentals, get_fundamental_summary, compare_fundamentals],
            instructions="""你是一个专业的基本面分析师，专注于股票基本面分析，具备以下能力：

1. **财务指标分析**
   - 深度解读财务报表数据
   - 评估盈利能力、成长性、财务健康状况
   - 计算和分析各种财务比率

2. **价值评估**
   - 估值模型应用（PE、PB、DCF等）
   - 内在价值计算
   - 相对估值分析

3. **行业分析**
   - 行业发展趋势分析
   - 竞争格局评估
   - 宏观经济影响分析

4. **投资建议**
   - 综合基本面因素给出投资建议
   - 风险因素识别和评估
   - 长期投资价值判断

当前基本面分析状态: {fundamental_analysis}

请基于基本面分析方法，为用户提供专业的股票价值评估服务。""",
            add_state_in_messages=True,
            show_tool_calls=True,
            markdown=True
        )
        
        logger.info("基本面分析智能体初始化完成")
    
    def _calculate_fundamental_scores(self, financial_metrics) -> Dict[str, float]:
        """计算基本面评分（优化版）"""
        scores = {}

        # 1. 盈利能力评分（三个指标，权重均等）
        scores["profitability"] = self._calculate_profitability_score(financial_metrics)

        # 2. 成长性评分（三个增长指标）
        scores["growth"] = self._calculate_growth_score(financial_metrics)

        # 3. 财务健康评分（流动性+债务+现金流）
        scores["financial_health"] = self._calculate_financial_health_score(financial_metrics)

        # 4. 估值评分（PE+PB+PS综合）
        scores["valuation"] = self._calculate_valuation_score(financial_metrics)

        return scores

    def _calculate_profitability_score(self, fm) -> float:
        """计算盈利能力评分"""
        # 获取指标值
        roe = fm.return_on_equity or 0
        net_margin = fm.net_margin or 0
        operating_margin = fm.operating_margin or 0

        # 分项评分（基于A股市场合理标准）
        # ROE评分：15%为满分，每降低1%扣0.67分
        roe_score = min(10, max(0, 10 - (0.15 - roe) * 67)) if roe > 0 else 0

        # 净利率评分：10%为满分，每降低1%扣1分
        net_margin_score = min(10, max(0, 10 - (0.10 - net_margin) * 100)) if net_margin > 0 else 0

        # 营业利润率评分：12%为满分，每降低1%扣0.83分
        op_margin_score = min(10, max(0, 10 - (0.12 - operating_margin) * 83)) if operating_margin > 0 else 0

        # 加权平均（ROE权重40%，净利率30%，营业利润率30%）
        profitability_score = (roe_score * 0.4 + net_margin_score * 0.3 + op_margin_score * 0.3)

        return round(profitability_score, 2)

    def _calculate_growth_score(self, fm) -> float:
        """计算成长性评分"""
        # 获取增长指标
        revenue_growth = fm.revenue_growth or 0
        earnings_growth = fm.earnings_growth or 0
        book_value_growth = fm.book_value_growth or 0

        # 分项评分（考虑负增长惩罚）
        def growth_score_func(growth_rate, excellent_threshold=0.20):
            if growth_rate >= excellent_threshold:
                return 10
            elif growth_rate >= 0.10:
                return 5 + (growth_rate - 0.10) * 50  # 10%-20%之间线性增长
            elif growth_rate >= 0:
                return growth_rate * 50  # 0%-10%之间
            else:
                return max(0, 5 + growth_rate * 25)  # 负增长重罚

        revenue_score = growth_score_func(revenue_growth, 0.15)
        earnings_score = growth_score_func(earnings_growth, 0.20)
        book_value_score = growth_score_func(book_value_growth, 0.12)

        # 加权平均（营收40%，利润40%，净资产20%）
        growth_score = (revenue_score * 0.4 + earnings_score * 0.4 + book_value_score * 0.2)

        return round(growth_score, 2)

    def _calculate_financial_health_score(self, fm) -> float:
        """计算财务健康评分"""
        # 获取财务健康指标
        current_ratio = fm.current_ratio or 1.0
        debt_to_equity = fm.debt_to_equity or 0.5
        free_cash_flow_per_share = fm.free_cash_flow_per_share or 0
        earnings_per_share = fm.earnings_per_share or 0.01

        # 1. 流动性评分（流动比率）
        # 2.0为满分，1.5为良好，1.0为及格线，1.0以下为危险
        if current_ratio >= 2.0:
            liquidity_score = 10
        elif current_ratio >= 1.5:
            liquidity_score = 5 + (current_ratio - 1.5) * 10  # 1.5-2.0之间：5-10分
        elif current_ratio >= 1.0:
            liquidity_score = 2 + (current_ratio - 1.0) * 6   # 1.0-1.5之间：2-5分
        else:
            liquidity_score = max(0, current_ratio * 2)       # 1.0以下：0-2分

        # 2. 债务健康评分（资产负债率）
        # 30%以下为优秀，50%以下为良好，70%以上为危险
        if debt_to_equity <= 0.30:
            debt_score = 10
        elif debt_to_equity <= 0.50:
            debt_score = 10 - (debt_to_equity - 0.30) * 25  # 30%-50%之间
        elif debt_to_equity <= 0.70:
            debt_score = 5 - (debt_to_equity - 0.50) * 12.5  # 50%-70%之间
        else:
            debt_score = max(0, 2.5 - (debt_to_equity - 0.70) * 8.33)  # 70%以上重罚

        # 3. 现金流质量评分
        # 现金流/每股收益比率，1.0以上为优秀
        if earnings_per_share > 0:
            cash_flow_ratio = free_cash_flow_per_share / earnings_per_share
            if cash_flow_ratio >= 1.0:
                cash_flow_score = 10
            elif cash_flow_ratio >= 0.8:
                cash_flow_score = 5 + (cash_flow_ratio - 0.8) * 25    # 0.8-1.0：5-10分
            elif cash_flow_ratio >= 0.5:
                cash_flow_score = 1 + (cash_flow_ratio - 0.5) * 13.33 # 0.5-0.8：1-5分
            else:
                cash_flow_score = max(0, cash_flow_ratio * 2)         # <0.5：0-1分
        else:
            cash_flow_score = 5  # 默认中性评分

        # 加权平均（流动性40%，债务40%，现金流20%）
        health_score = (liquidity_score * 0.4 + debt_score * 0.4 + cash_flow_score * 0.2)

        return round(health_score, 2)

    def _calculate_valuation_score(self, fm) -> float:
        """计算估值评分"""
        # 获取估值指标
        pe_ratio = fm.pe_ratio or 25
        pb_ratio = fm.price_to_book or 2.5
        ps_ratio = fm.price_to_sales or 4.0

        # 1. PE评分（市盈率）
        # 15倍为理想，25倍为合理上限，40倍以上为高估
        # 要考虑公司的板块以及发展阶段，如果公司处于高速成长期，可以适当提高PE评分，后续交由LLM判断
        if pe_ratio <= 15:
            pe_score = 10
        elif pe_ratio <= 25:
            pe_score = 10 - (pe_ratio - 15) * 0.5  # 15-25倍之间
        elif pe_ratio <= 40:
            pe_score = 5 - (pe_ratio - 25) * 0.2  # 25-40倍之间
        else:
            pe_score = max(0, 2 - (pe_ratio - 40) * 0.05)  # 40倍以上重罚

        # 2. PB评分（市净率）
        # 1.5倍为理想，3倍为合理上限，5倍以上为高估
        # 要考虑公司的板块以及发展阶段，如果公司处于高速成长期，可以适当提高PB评分，后续交由LLM判断
        if pb_ratio <= 1.5:
            pb_score = 10
        elif pb_ratio <= 3.0:
            pb_score = 10 - (pb_ratio - 1.5) * 3.33  # 1.5-3倍之间
        elif pb_ratio <= 5.0:
            pb_score = 5 - (pb_ratio - 3.0) * 1.5  # 3-5倍之间
        else:
            pb_score = max(0, 2 - (pb_ratio - 5.0) * 0.4)  # 5倍以上重罚

        # 3. PS评分（市销率）
        # 2倍为理想，5倍为合理上限，8倍以上为高估
        if ps_ratio <= 2.0:
            ps_score = 10
        elif ps_ratio <= 5.0:
            ps_score = 10 - (ps_ratio - 2.0) * 2.33  # 2-5倍之间：10分→3分
        elif ps_ratio <= 8.0:
            ps_score = 3 - (ps_ratio - 5.0) * 1.0   # 5-8倍之间：3分→0分
        else:
            ps_score = max(0, 0 - (ps_ratio - 8.0) * 0.1)  # 8倍以上：接近0分

        # 加权平均（PE 50%，PB 30%，PS 20%）
        valuation_score = (pe_score * 0.5 + pb_score * 0.3 + ps_score * 0.2)

        return round(valuation_score, 2)
    
    def _determine_signal_and_confidence(self, scores: Dict[str, float]) -> tuple:
        """确定信号和置信度（加权平均版）"""
        if not scores:
            return "neutral", 0.5

        # 设定各维度权重（基于重要性）
        weights = {
            "profitability": 0.35,    # 盈利能力最重要
            "growth": 0.25,           # 成长性次之
            "financial_health": 0.20, # 财务健康同样重要
            "valuation": 0.20         # 估值相对次要（短期影响较小）
        }


        # 计算加权平均分
        weighted_score = 0
        total_weight = 0

        for dimension, score in scores.items():
            if dimension in weights:
                weighted_score += score * weights[dimension]
                total_weight += weights[dimension]

        # 如果有未知维度，使用等权重处理
        if total_weight < 1.0:
            remaining_weight = 1.0 - total_weight
            unknown_dimensions = [d for d in scores.keys() if d not in weights]
            if unknown_dimensions:
                equal_weight = remaining_weight / len(unknown_dimensions)
                for dimension in unknown_dimensions:
                    weighted_score += scores[dimension] * equal_weight

        avg_score = weighted_score

        if avg_score >= 7:
            return "bullish", min(0.9, avg_score / 10)
        elif avg_score <= 4:
            return "bearish", min(0.9, (10 - avg_score) / 10)
        else:
            return "neutral", 0.5

    def _add_financial_metrics_descriptions(self, financial_data: Dict[str, Any]) -> Dict[str, Any]:
        """为财务指标添加中文描述（从FinancialMetrics模型中读取）"""
        if not financial_data:
            return {}

        # 从FinancialMetrics模型中获取字段描述
        from ..models.market_data import FinancialMetrics

        # 构建带描述的数据
        result = {}
        for key, value in financial_data.items():
            # 获取字段的描述信息
            field_info = FinancialMetrics.model_fields.get(key)
            if field_info and hasattr(field_info, 'description') and field_info.description:
                description = field_info.description
                result[f"{key}({description})"] = value
            else:
                result[key] = value

        # print(result)
        # print('-'*100)
        return result

    def _add_market_data_descriptions(self, market_data: Dict[str, Any]) -> Dict[str, Any]:
        """为市场数据添加中文描述（从MarketData模型中读取）"""
        if not market_data:
            return {}

        # 从MarketData模型中获取字段描述
        from ..models.market_data import MarketData

        # 构建带描述的数据
        result = {}
        for key, value in market_data.items():
            # 获取字段的描述信息
            field_info = MarketData.model_fields.get(key)
            if field_info and hasattr(field_info, 'description') and field_info.description:
                description = field_info.description
                result[f"{key}({description})"] = value
            else:
                result[key] = value

        # print(result)
        # print('-'*100)
        return result
    
    def run(self, message: str, **kwargs) -> str:
        """运行智能体"""
        try:
            response = self.agent.run(message, **kwargs)
            # 正确处理RunResponse对象
            if response:
                if hasattr(response, 'content'):
                    return str(response.content) if response.content else "执行失败，未收到响应内容"
                else:
                    return str(response) if response else "执行失败，响应为空"
            else:
                return "执行失败，未收到响应"
        except Exception as e:
            error_msg = f"基本面分析智能体执行失败: {str(e)}"
            logger.error(error_msg)
            return error_msg
    
    def print_response(self, message: str, stream: bool = True, **kwargs):
        """打印智能体响应"""
        self.agent.print_response(message, stream=stream, **kwargs)

    def get_analysis_result(self, ticker: str) -> Optional[Dict[str, Any]]:
        """获取基本面分析结果"""
        return self.agent.workflow_session_state.get("fundamental_analysis", {}).get(ticker)
    
